package com.easybacklog.client.cucumberfeatures.edit;

import java.util.Date;

import com.easybacklog.client.EasyBacklogGlobalVariables;
import com.easybacklog.client.EasyBacklogPage;
import com.easybacklog.client.InitializeEasyBacklog;
import com.easybacklog.client.model.ProjectFeature;
import com.easybacklog.client.utilities.FileNameGenerator;
import com.easybacklog.client.webservices.RequestSaveLiveFeed;
import com.easybacklog.client.webservices.subversion.RequestSaveFeatureSubversionRepository;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;

/**
 * 
 * @UserInterface
 */
public class ButtonSaveBacklogFeature extends Button {

	public ButtonSaveBacklogFeature(final ProjectFeature feature) {

		this.setText("Save");

		this.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				ProjectFeature newFeature = getProjectBacklog(feature);

				EasyBacklogGlobalVariables.projectFeatures.put(
						newFeature.toString(), newFeature);

				RequestSaveFeatureSubversionRepository.sendPostRequest(
						EasyBacklogGlobalVariables.currentProject, newFeature);

				RequestSaveLiveFeed.feedUpdateFeature(
						EasyBacklogGlobalVariables.userID, newFeature);

				InitializeEasyBacklog.vpBacklog.clear();
				InitializeEasyBacklog.vpBacklog.add(new EasyBacklogPage());
			}
		});
	}

	private ProjectFeature getProjectBacklog(final ProjectFeature backlogEntry) {

		String featureName = BacklogFeatureForm.featureName.getValue();

		backlogEntry.setFeatureName(featureName);

		backlogEntry
				.setFileExtension(EasyBacklogGlobalVariables.featureFileExtension);

		backlogEntry.setDateModified(new Date());

		String fileName = FileNameGenerator.compactName(featureName) + "."
				+ EasyBacklogGlobalVariables.featureFileExtension;

		backlogEntry.setFileName(fileName);

		backlogEntry.setFilePath(EasyBacklogGlobalVariables.featuresPath);

		backlogEntry.setFeatureDescription(BacklogFeatureForm.featureDescription
				.getValue());

		if (BacklogFeatureForm.featurePriority.getValue() != null
				&& BacklogFeatureForm.featurePriority.getValue().length() > 0) {

			backlogEntry.setPriority(new Integer(BacklogFeatureForm.featurePriority
					.getValue()));
		}

		if (BacklogFeatureForm.featureEstimate.getValue() != null
				&& BacklogFeatureForm.featureEstimate.getValue().length() > 0) {

			backlogEntry.setEstimate(new Integer(BacklogFeatureForm.featureEstimate
					.getValue()));
		}

		backlogEntry.setStatus(BacklogFeatureForm.featureStatus
				.getValue(BacklogFeatureForm.featureStatus.getSelectedIndex()));

		return backlogEntry;
	}
}